package cn.koalsc.btclient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
//import android.content.Context;
//import android.util.Log;

public class SwipeCardController
{
  private BluetoothSocket mSocket = null;
  private OnBluetoothDataListener mOnPortListener;
  private static final String TAG = "BusinessBluetooth";
  private InputStream mInputStream;
  private OutputStream mOutputStream;
  private byte[] resultdata_buffer = null;
  private static String cardCip = "";
  private static String track2Cip = "";
  private static String track3Cip = "";
  private static String pinCip = "";
  private static String moneyCip = "";
  private static String randomCip = "";
  private static boolean newDevice = false;
  private boolean oldDevice = false;
  private static boolean calcMac = false;
  private static String macData;
  private static byte[] factorByte;
  Bundle bData;
  private byte cmdCode;
  Bundle bundle;
  
  public SwipeCardController(OnBluetoothDataListener listener, BluetoothSocket socket)
  {
    this.mSocket = socket;
    this.mOnPortListener = listener;
  }
  
  public void getDeviceType()
  {
    byte[] cmd = { 4 };
    
    SendingandReceiving(cmd, cmd.length, 3000);
  }
  
  public String getKsn()
  {
    byte[] command = { 5 };
    
    SendingandReceiving(command, command.length, 3000);
    
    return null;
  }
  
  public void encyptData(String keyIndex, String data, String factor)
    throws TimeoutException
  {
    String dataEnc = null;
    if (keyIndex.equals("15"))
    {
      factorByte = HexString2Bytes(factor);
      int a = factorByte.length;
      
      byte[] ds = new byte[a + 1];
      ds[0] = 14;
      for (int i = 0; i < a; i++) {
        ds[(1 + i)] = factorByte[i];
      }
      macData = data;
      calcMac = true;
      SendingandReceiving(ds, ds.length, 3000);
    }
    else if (keyIndex.equals("13"))
    {
      boolean digit = isDigit(data);
      boolean digit2 = isDigit(data);
      if ((!digit) && (!digit2)) {
        return;
      }
      if ((data.length() >= 16) && (data.length() % 8 == 0))
      {
        byte[] factorByte = HexString2Bytes(factor);
        byte[] dataByte = HexString2Bytes(data);
        int a = factorByte.length;
        int b = dataByte.length;
        byte[] ds = new byte[a + 1 + dataByte.length];
        ds[0] = 7;
        for (int i = 0; i < a; i++) {
          ds[(1 + i)] = factorByte[i];
        }
        for (int i = 0; i < dataByte.length; i++) {
          ds[(a + 1 + i)] = dataByte[i];
        }
        SendingandReceiving(ds, ds.length, 3000);
      }
      else {}
    }
  }
  
  public String registerPwd(int timeout, String factor)
    throws TimeoutException
  {
    boolean digit = isDigit(factor);
    if ((16 != factor.length()) || (!digit)) {
      return "07";
    }
    byte[] factorByte = HexString2Bytes(factor);
    int len = factorByte.length;
    byte[] ds = new byte[len + 1 + 2];
    if (timeout == 0) {
      return "07";
    }
    int time = timeout * 1000;
    ds[0] = 6;
    String hexStr = Integer.toHexString(time);
    StringBuilder builder = new StringBuilder();
    if (hexStr.length() == 3)
    {
      builder.append("0");
      builder.append(hexStr);
    }
    else if (hexStr.length() == 2)
    {
      builder.append("00");
      builder.append(hexStr);
    }
    else
    {
      builder.append(hexStr);
    }
    byte[] charArray1 = HexString2Bytes(builder.toString());
    for (int i = 0; i < charArray1.length; i++) {
      ds[(1 + i)] = charArray1[i];
    }
    for (int i = 0; i < len; i++) {
      ds[(1 + i + 2)] = factorByte[i];
    }
    String encode = "";
    
    SendingandReceiving(ds, ds.length, time);
    if (encode == null) {
      return "01";
    }
    if ("03".equals(encode)) {
      return "05";
    }
    if ("extraction".equals(encode)) {
      return "09";
    }
    return encode;
  }
  
  public boolean affirmAmount(String amount, int timeout)
    throws TimeoutException
  {
    boolean digit = isDigit2(amount);
    if (amount.length() != 10) {
      return false;
    }
    if (!digit) {
      return false;
    }
    int time = timeout * 1000;
    String moneyStr = null;
    boolean flag = false;
    

    byte[] ds = new byte[8];
    ds[0] = 8;
    
    String hexStr = Integer.toHexString(time);
    byte[] charArray1 = HexString2Bytes(hexStr);
    for (int i = 0; i < charArray1.length; i++) {
      ds[(1 + i)] = charArray1[i];
    }
    byte[] charArray2 = HexString2Bytes(amount);
    for (int i = 0; i < charArray2.length; i++) {
      ds[(3 + i)] = charArray2[i];
    }
    SendingandReceiving(ds, ds.length, time);
    
    return flag;
  }
  
  public static byte[] clacMac(byte[] key, byte[] Input)
    throws Exception
  {
    int length = Input.length;
    int x = length % 8;
    int addLen = 0;
    if (x != 0) {
      addLen = 8 - length % 8;
    }
    int pos = 0;
    byte[] data = new byte[length + addLen];
    System.arraycopy(Input, 0, data, 0, length);
    byte[] oper1 = new byte[8];
    System.arraycopy(data, pos, oper1, 0, 8);
    for (int i = 1; i <= data.length / 8; i++)
    {
      byte[] oper2 = new byte[8];
      System.arraycopy(data, pos, oper2, 0, 8);
      

      byte[] t = null;
      if (i == 1) {
        t = bytesXOR(oper1, parseHexStr2Byte("0000000000000000"));
      } else {
        t = bytesXOR(oper1, oper2);
      }
      oper1 = TriDesEncryption(key, t);
      pos += 8;
    }
    byte[] buff = oper1;
    
    byte[] retBuf = new byte[4];
    System.arraycopy(buff, 0, retBuf, 0, 4);
    return retBuf;
  }
  
  public static byte[] bytesXOR(byte[] src, byte[] src1)
  {
    int length = src.length;
    if (length != src1.length) {
      return null;
    }
    byte[] result = new byte[length];
    for (int i = 0; i < length; i++) {
      result[i] = byteXOR(src[i], src1[i]);
    }
    return result;
  }
  
  public static byte byteXOR(byte src, byte src1)
  {
    return (byte)(src & 0xFF ^ src1 & 0xFF);
  }
  
  private static byte[] TriDesEncryption(byte[] byteKey, byte[] dec)
  {
    try
    {
      byte[] en_key = new byte[24];
      if (byteKey.length == 16)
      {
        System.arraycopy(byteKey, 0, en_key, 0, 16);
        System.arraycopy(byteKey, 0, en_key, 16, 8);
      }
      else if (byteKey.length == 8)
      {
        System.arraycopy(byteKey, 0, en_key, 0, 8);
        System.arraycopy(byteKey, 0, en_key, 8, 8);
        System.arraycopy(byteKey, 0, en_key, 16, 8);
      }
      else
      {
        en_key = byteKey;
      }
      SecretKeySpec key = new SecretKeySpec(en_key, "DESede");
      
      Cipher ecipher = Cipher.getInstance("DESede/ECB/NoPadding");
      ecipher.init(1, key);
      

      return ecipher.doFinal(dec);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }
  
  private byte[] TriDesDecryption(byte[] byteKey, byte[] dec)
  {
    byte[] en_key = new byte[24];
    if (byteKey.length == 16)
    {
      System.arraycopy(byteKey, 0, en_key, 0, 16);
      System.arraycopy(byteKey, 0, en_key, 16, 8);
    }
    else if (byteKey.length == 8)
    {
      System.arraycopy(byteKey, 0, en_key, 0, 8);
      System.arraycopy(byteKey, 0, en_key, 8, 8);
      System.arraycopy(byteKey, 0, en_key, 16, 8);
    }
    else
    {
      en_key = byteKey;
    }
    SecretKey key = null;
    try
    {
      key = new SecretKeySpec(en_key, "DESede");
    }
    catch (Exception e)
    {
      e.printStackTrace();
      return null;
    }
    try
    {
      Cipher dcipher = Cipher.getInstance("DESede/ECB/NoPadding");
      dcipher.init(2, key);
      



      return dcipher.doFinal(dec);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }
  
  public void stopOperate()
  {
    byte[] cmd = { 3 };
    
    SendingandReceiving(cmd, cmd.length, 1000);
  }
  
  public void swipe(int timeout, String factor)
  {
    int time = timeout * 1000;
    byte[] factorByte = HexString2Bytes(factor);
    int len = factorByte.length;
    byte[] ds = new byte[len + 1 + 2];
    if (newDevice) {
      ds[0] = 12;
    } else {
      ds[0] = 9;
    }
    String hexStr = Integer.toHexString(time);
    StringBuilder builder = new StringBuilder();
    if (hexStr.length() == 3)
    {
      builder.append("0");
      builder.append(hexStr);
    }
    else if (hexStr.length() == 2)
    {
      builder.append("00");
      builder.append(hexStr);
    }
    else
    {
      builder.append(hexStr);
    }
    byte[] charArray1 = HexString2Bytes(builder.toString());
    for (int i = 0; i < charArray1.length; i++) {
      ds[(1 + i)] = charArray1[i];
    }
    for (int i = 0; i < len; i++) {
      ds[(1 + i + 2)] = factorByte[i];
    }
    SendingandReceiving(ds, ds.length, time);
  }
  
  public int inputPwd(int timeout, String factor)
    throws TimeoutException
  {
    int time = timeout * 1000;
    String encode = null;
    byte[] ds = new byte[11];
//    System.out.println("newDevice==" + newDevice);
    if (newDevice) {
      ds[0] = 13;
    } else {
      ds[0] = 10;
    }
    String hexStr = Integer.toHexString(time);
    StringBuilder builder1 = new StringBuilder();
    if (hexStr.length() == 3)
    {
      builder1.append("0");
      builder1.append(hexStr);
    }
    else if (hexStr.length() == 2)
    {
      builder1.append("00");
      builder1.append(hexStr);
    }
    else
    {
      builder1.append(hexStr);
    }
    byte[] charArray1 = HexString2Bytes(builder1.toString());
    for (int i = 0; i < charArray1.length; i++) {
      ds[(1 + i)] = charArray1[i];
    }
    byte[] byte1 = parseHexStr2Byte(factor);
    for (int i = 0; i < byte1.length; i++) {
      ds[(3 + i)] = byte1[i];
    }
    SendingandReceiving(ds, ds.length, time);
    
    return 0;
  }
  
  public void selectDirectory(int tag)
  {
//    System.out.println("閫夋嫨鐩綍");
    byte[] my_cmdbuf = new byte[8];
    my_cmdbuf[0] = -86;
    my_cmdbuf[1] = 4;
    my_cmdbuf[2] = -79;
    my_cmdbuf[3] = 1;
    my_cmdbuf[4] = 63;
    if (1 == tag)
    {
      my_cmdbuf[5] = 17;
      newDevice = true;
    }
    else if (2 == tag)
    {
      my_cmdbuf[5] = 1;
      newDevice = false;
    }
    my_cmdbuf[6] = -18;
    my_cmdbuf[7] = 0;
    my_cmdbuf[7] = ((byte)Senddata_LRCcheck(my_cmdbuf));
    try
    {
      if (this.mSocket == null) {
        return;
      }
      OutputStream os = this.mSocket.getOutputStream();
      os.write(my_cmdbuf);
      
      os.flush();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
  
  public void receiveData()
  {
    byte[] buffer = new byte[1024];
    int bytes = 0;
    InputStream mmInStream = null;
    try
    {
      mmInStream = this.mSocket.getInputStream();
    }
    catch (IOException e1)
    {
      e1.printStackTrace();
    }
    StringBuilder builder = new StringBuilder();
    try
    {
      mmInStream = this.mSocket.getInputStream();
    }
    catch (IOException e2)
    {
      e2.printStackTrace();
    }
    boolean flag = true;
    for (;;)
    {
      String dataStr = "";
      boolean mFlag = false;
      boolean macF = false;
      try
      {
        while (mmInStream.available() == 0) {}
        flag = true;
        while (flag)
        {
          bytes = mmInStream.read(buffer);
          String HexStr = byteArr2HexStr(buffer, bytes);
          
          dataStr = dataStr + HexStr;
          if (mmInStream.available() == 0)
          {
            int len = dataStr.length();
            if (len > 4)
            {
              String substring = dataStr.substring(len - 4, len - 2);
              if ("aa".equals(substring)) {
                flag = false;
              }
            }
          }
        }
        String cmd = null;
        if ((!"bb".equals(dataStr.substring(0, 2))) && 
          (dataStr.indexOf("bb") > 0))
        {
          String allData = dataStr
            .substring(dataStr.indexOf("bb"), 
            dataStr.length());
          boolean check = check(HexString2Bytes(allData));
          if (!check) {
            return;
          }
          if (allData.length() > 15) {
            cmd = allData.substring(4, 6);
          } else {
            cmd = allData.substring(2, 4);
          }
        }
        else
        {
          boolean check = check(HexString2Bytes(dataStr));
          if (!check) {
            return;
          }
          if (dataStr.length() > 15) {
            cmd = dataStr.substring(4, 6);
          } else {
            cmd = dataStr.substring(2, 4);
          }
        }
        String resultStr = GetResultDataAsHexString();
//        System.out.println("杩斿洖鏁版嵁==" + resultStr);
        
        int tag = 0;
        
        HashMap<String, String> hashMap = null;
        if ("05".equals(cmd))
        {
          if (resultStr.length() > 36) {
            resultStr = resultStr.substring(2, resultStr.length());
          }
          resultStr = changeHexString2CharString(resultStr);
          tag = 1;
        }
        else if (calcMac)
        {
          tag = 6;
          calcMac = false;
          if (resultStr.length() == 2) {
            continue;
          }
          String macKeyStr = resultStr;
          if (macKeyStr.length() > 20)
          {
            byte[] pngKey = TriDesEncryption(factorByte, parseHexStr2Byte(macKeyStr.substring(0, 16)));
            if (pngKey == null) {
              return;
            }
            byte[] macKey = TriDesDecryption(pngKey, parseHexStr2Byte(macKeyStr
              .substring(16, macKeyStr.length())));
//            System.out.println("mac1==" + byteArr2HexStr(macKey));
            macKey = TriDesEncryption(macKey, factorByte);
//            System.out.println("mac2==" + byteArr2HexStr(macKey));
            try
            {
              resultStr = byteArr2HexStr(clacMac(macKey, parseHexStr2Byte(macData + "8000000000000000")));
//              System.out.println("mac==" + resultStr);
            }
            catch (Exception e)
            {
              e.printStackTrace();
            }
          }
        }
        else if ("0c".equals(cmd))
        {
          tag = 3;
          mFlag = true;
          this.bData = swipeData(resultStr);
        }
        else if ("09".equals(cmd))
        {
          tag = 8;
          mFlag = true;
          this.bData = swipeData2(resultStr);
        }
        else if ("0a".equals(cmd))
        {
          tag = 9;
          mFlag = true;
          pwd2(resultStr);
        }
        else if ("08".equals(cmd))
        {
          tag = 2;
        }
        else if ("0d".equals(cmd))
        {
          tag = 4;
          mFlag = true;
          pwd(resultStr);
        }
        else if ("06".equals(cmd))
        {
          tag = 5;
        }
        else if ("07".equals(cmd))
        {
          tag = 7;
        }
        if (mFlag) {
          this.mOnPortListener.onReceiveData("01", this.bData, tag);
        } else {
          this.mOnPortListener.onReceiveData(resultStr, null, tag);
        }
        builder = new StringBuilder();
        builder.delete(0, builder.length());
        dataStr = "";
      }
      catch (IOException e)
      {
        try
        {
          builder = new StringBuilder();
          builder.delete(0, builder.length());
          mmInStream.close();
        }
        catch (IOException e1)
        {
          e1.printStackTrace();
        }
      }
    }
  }
  
  public static String byteArr2HexStr(byte[] arrB, int iLen)
  {
    StringBuffer sb = new StringBuffer(iLen * 2);
    for (int i = 0; i < iLen; i++)
    {
      int intTmp = arrB[i];
      while (intTmp < 0) {
        intTmp += 256;
      }
      if (intTmp < 16) {
        sb.append("0");
      }
      sb.append(Integer.toString(intTmp, 16));
    }
    return sb.toString();
  }
  
  public static String byteArr2HexStr(byte[] arrB)
  {
    int iLen = arrB.length;
    
    StringBuffer sb = new StringBuffer(iLen * 2);
    for (int i = 0; i < iLen; i++)
    {
      int intTmp = arrB[i];
      while (intTmp < 0) {
        intTmp += 256;
      }
      if (intTmp < 16) {
        sb.append("0");
      }
      sb.append(Integer.toString(intTmp, 16));
    }
    return sb.toString();
  }
  
  public static String parseByte2HexStr(byte[] buf)
  {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < buf.length; i++)
    {
      String hex = Integer.toHexString(buf[i] & 0xFF);
      if (hex.length() == 1) {
        hex = '0' + hex;
      }
      sb.append(hex.toUpperCase());
    }
    return sb.toString();
  }
  
  private String changeHexString2CharString(String e)
  {
    String char_txt = "";
    for (int i = 0; i < e.length(); i += 2)
    {
      String c = e.substring(i, i + 2);
      char j = (char)Integer.parseInt(c, 16);
      char_txt = char_txt + j;
    }
    return char_txt;
  }
  
  public static byte[] parseHexStr2Byte(String hexStr)
  {
    if (hexStr.length() < 1) {
      return null;
    }
    byte[] result = new byte[hexStr.length() / 2];
    for (int i = 0; i < hexStr.length() / 2; i++)
    {
      int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
      int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 
        16);
      result[i] = ((byte)(high * 16 + low));
    }
    return result;
  }
  
  public static byte[] HexString2Bytes(String hexstr)
  {
    byte[] b = new byte[hexstr.length() / 2];
    int j = 0;
    for (int i = 0; i < b.length; i++)
    {
      char c0 = hexstr.charAt(j++);
      char c1 = hexstr.charAt(j++);
      b[i] = ((byte)(parseStr(c0) << 4 | parseStr(c1)));
    }
    return b;
  }
  
  private static int parseStr(char c)
  {
    if (c >= 'a') {
      return c - 'a' + 10 & 0xF;
    }
    if (c >= 'A') {
      return c - 'A' + 10 & 0xF;
    }
    return c - '0' & 0xF;
  }
  
  public void SendingandReceiving(byte[] Data, int Datalength, int millis)
  {
    int i = 0;
    byte[] my_cmdbuf = null;
    if (Datalength == 1)
    {
      my_cmdbuf = new byte[Datalength + 4];
      my_cmdbuf[0] = -86;
      my_cmdbuf[1] = ((byte)Datalength);
      for (; i < Datalength; i++) {
        my_cmdbuf[(i + 2)] = Data[i];
      }
      my_cmdbuf[(i + 2)] = -18;
      my_cmdbuf[(i + 3)] = 0;
      my_cmdbuf[(i + 3)] = ((byte)Senddata_LRCcheck(my_cmdbuf));
    }
    else
    {
      my_cmdbuf = new byte[Datalength + 5];
      my_cmdbuf[0] = -86;
      my_cmdbuf[1] = ((byte)(Datalength + 1));
      my_cmdbuf[2] = Data[i];
      i++;
      my_cmdbuf[3] = ((byte)(Datalength - 1));
      for (; i < Datalength; i++) {
        my_cmdbuf[(i + 3)] = Data[i];
      }
      my_cmdbuf[(i + 3)] = -18;
      my_cmdbuf[(i + 4)] = 0;
      my_cmdbuf[(i + 4)] = ((byte)Senddata_LRCcheck(my_cmdbuf));
    }
//    System.out.println("sendData==" + byteArr2HexStr(my_cmdbuf));
    try
    {
      if (this.mSocket == null) {
        return;
      }
      OutputStream os = this.mSocket.getOutputStream();
      os.write(my_cmdbuf);
      
      os.flush();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
  
  private int Senddata_LRCcheck(byte[] my_cmdbuf)
  {
    int j = 0;
    byte edc = 0;
    int len = my_cmdbuf.length;
    for (j = 0; j < len; j++) {
      edc = (byte)(edc ^ my_cmdbuf[j]);
    }
    return edc;
  }
  
  public static boolean isDigit2(String strNum)
  {
    return strNum.matches("[0-9]{1,}");
  }
  
  private boolean check(byte[] buffer)
  {
    int len = buffer.length;
    boolean flag = false;
    if (len > 5)
    {
      //        Log.e("BusinessBluetooth", "data check false");
      flag = ProcessDataResult(buffer, len);
    }
    else //      Log.e("BusinessBluetooth", "鐘舵�鐮�data check  false");
      flag = ProcessDataResult2(buffer, len);
    return flag;
  }
  
  private boolean ProcessDataResult(byte[] buffer, int len)
  {
    this.cmdCode = 0;
    int edc = 0;
    int etx = 0;
    int Stx = 187;
    int Etx = 170;
    int Starting_byte = 0;
    this.resultdata_buffer = null;
    for (Starting_byte = 0; Starting_byte < len; Starting_byte++) {
      if ((buffer[Starting_byte] & 0xFF) == Stx) {
        break;
      }
    }
    if ((buffer[(0 + Starting_byte)] & 0xFF) != Stx)
    {
//      Log.e("BusinessBluetooth", "甯уご閿欒 Error 02");
      return false;
    }
    int data_len = buffer[(1 + Starting_byte)] & 0xFF;
    if (data_len + 3 > len - Starting_byte)
    {
//      Log.e("BusinessBluetooth", "鏁版嵁缂哄け Error 03");
      return false;
    }
    etx = buffer[(2 + data_len + Starting_byte)] & 0xFF;
    if (etx != Etx)
    {
//      Log.e("BusinessBluetooth", "甯у熬閿欒 Error 05");
      return false;
    }
    edc = 0;
    for (int i = 0; i < data_len + 3; i++) {
      edc ^= buffer[(i + Starting_byte)];
    }
    if (edc != buffer[(3 + data_len + Starting_byte)])
    {
//      Log.e("BusinessBluetooth", "鏍￠獙閿欒  Error 06");
      return false;
    }
    this.resultdata_buffer = new byte[data_len - 1];
    for (int n = 0; n < data_len - 1; n++) {
      this.resultdata_buffer[n] = buffer[(3 + n + Starting_byte)];
    }
    return true;
  }
  
  private boolean ProcessDataResult2(byte[] buffer, int len)
  {
    this.cmdCode = 0;
    int edc = 0;
    int etx = 0;
    int Stx = 187;
    int Etx = 170;
    int Starting_byte = 0;
    this.resultdata_buffer = null;
    for (Starting_byte = 0; Starting_byte < len; Starting_byte++) {
      if ((buffer[Starting_byte] & 0xFF) == Stx) {
        break;
      }
    }
    if ((buffer[(0 + Starting_byte)] & 0xFF) != Stx) {
      return false;
    }
    if (2 > len - 3)
    {
//      Log.e("BusinessBluetooth", "鐘舵�鐮佹暟鎹己澶�Error 03");
      return false;
    }
    etx = buffer[(3 + Starting_byte)] & 0xFF;
    if (etx != Etx)
    {
//      Log.e("BusinessBluetooth", "鐘舵�鐮佸抚灏鹃敊璇�Error 05");
      return false;
    }
    edc = 0;
    for (int i = 0; i < len - 1; i++) {
      edc ^= buffer[(i + Starting_byte)];
    }
    if (edc != buffer[(len - 1)])
    {
//      Log.e("BusinessBluetooth", "鐘舵�鐮佹牎楠岄敊璇� Error 06");
      return false;
    }
    this.resultdata_buffer = new byte[1];
    
    this.resultdata_buffer[0] = buffer[2];
    this.cmdCode = buffer[1];
    if (buffer[2] == 5) {
      this.cmdCode = 3;
    }
    return true;
  }
  
  private String GetResultDataAsHexString()
  {
    if (this.cmdCode == 3) {
      return "05";
    }
    if (this.resultdata_buffer == null) {
      return null;
    }
    String text = "";
    for (int i = 0; i < this.resultdata_buffer.length; i++) {
      text = 
        text + Integer.toHexString(
        this.resultdata_buffer[i] & 0xFF | 0xFFFFFF00)
        .substring(6);
    }
    this.resultdata_buffer = null;
    
    return text;
  }
  
  private Bundle swipeData(String encode)
  {
    if (this.bundle == null) {
      this.bundle = new Bundle();
    }
    if ((encode == null) || ("".equals(encode)))
    {
      this.bundle.putString("swipeState", "01");
    }
    else if ("05".equals(encode))
    {
      this.bundle.putString("swipeState", "05");
//      System.out.println("swipeController  鍙栨秷鍒峰崱");
    }
    else if ("03".equals(encode))
    {
      this.bundle.putString("swipeState", "03");
    }
    if (encode.length() > 22)
    {
      String dynamicKeyData = encode.substring(0, 16);
      
      this.bundle.putString("dynamicKeyData", dynamicKeyData);
      
      randomCip = dynamicKeyData;
      String track2_LenStr = encode.substring(16, 18);
      int track2_Len = Integer.parseInt(track2_LenStr, 16);
      String track2 = encode.substring(18, track2_Len + 18);
//      System.out.println("swipeDatatrack2==" + track2);
      this.bundle.putString("track2", track2);
      track2Cip = track2;
      String track3_LenStr = encode.substring(track2_Len + 18, 
        track2_Len + 20);
      int track3_Len = Integer.parseInt(track3_LenStr, 16);
      if (track3_Len > 0)
      {
        String track3 = encode.substring(track2_Len + 20, 
          track2_Len + 20 + track3_Len);
//        System.out.println("swipeDatatrack3==" + track3);
        this.bundle.putString("track3", track3);
        track3Cip = track3;
      }
      String cardNumLenStr = encode.substring(track2_Len + 20 + track3_Len, 
        track2_Len + 20 + track3_Len + 2);
      int cardNumLen = Integer.parseInt(cardNumLenStr, 16);
      
      String cardNum = encode.substring(track2_Len + 20 + track3_Len + 2, 
        track2_Len + 20 + track3_Len + 2 + cardNumLen);
      if (cardNum.length() < 10)
      {
        encode = "01";
        this.bundle.putString("cardNum", encode);
      }
      else
      {
        encode = cardNum;
        this.bundle.putString("cardNum", encode);
      }
      this.bundle.putString("swipeState", "00");
    }
    else
    {
      this.bundle.putString("swipeState", "01");
      if (this.bundle != null)
      {
        this.bundle.putString("CardNo", null);
        this.bundle.putString("track2", null);
        this.bundle.putString("track3", null);
      }
    }
    return this.bundle;
  }
  
  private Bundle swipeData2(String encode)
  {
    if (this.bundle == null) {
      this.bundle = new Bundle();
    }
    if (encode == null) {
      return null;
    }
    if (encode.equals("extraction")) {
      this.bundle.putString("swipeState", "09");
    } else if ("03".equals(encode)) {
      this.bundle.putString("swipeState", "03");
    }
    this.bundle.putString("swipeState", encode);
    return this.bundle;
  }
  
  private void pwd(String encode)
  {
    if (this.bundle == null) {
      return;
    }
    String cardNumLenStr = encode.substring(0, 2);
    int cardNumLen = Integer.parseInt(cardNumLenStr, 16);
    String cardNumCip = encode.substring(2, cardNumLen * 2 + 2);
    if (cardNumLen == 19) {
      cardNumCip = encode.substring(2, cardNumLen * 2 + 2).substring(0, 
        32);
    }
    this.bundle.putString("account", cardNumCip);
    cardCip = cardNumCip;
    String pin = encode.substring(cardNumLen * 2 + 2, (cardNumLen + 9) * 2);
    
    this.bundle.putString("pin", pin);
    pinCip = pin;
    String moneyStr = encode.substring((cardNumLen + 9) * 2, 
      2 * (cardNumLen + 9 + 16));
    
    this.bundle.putString("amount", moneyStr);
    moneyCip = moneyStr;
  }
  
  private void pwd2(String encode)
  {
    if (this.bundle == null) {
      return;
    }
    if ((encode == null) || ("".equals(encode)))
    {
      this.bundle.putString("swipeState", "01");
      return;
    }
    if ("03".equals(encode))
    {
      this.bundle.putString("swipeState", "05");
      return;
    }
    if ("extraction".equals(encode))
    {
      this.bundle.putString("swipeState", "09");
      return;
    }
    if ((encode != null) && (encode.length() > 16))
    {
      String g_CH1_Len = encode.substring(0, 2);
      int pwd1 = Integer.parseInt(g_CH1_Len, 16);
      if (pwd1 > 42)
      {
        this.bundle.putString("swipeState", "01");
        return;
      }
      String cardCip = encode.substring(2, 2 + 2 * pwd1);
      this.bundle.putString("account", cardCip);
      
      String str2Cip = "";
      String g_CH2_Len = encode.substring(2 * pwd1 + 2, 2 * pwd1 + 4);
      int str2Len = Integer.parseInt(g_CH2_Len, 16);
      
      str2Cip = encode.substring(2 * (pwd1 + 3), 
        2 * (pwd1 + 3 + str2Len));
      this.bundle.putString("track2", str2Cip);
//      System.out.println("pwd2str2Cip==" + str2Cip);
      String str3Cip = "";
      String g_CH3_Len = encode.substring(2 * pwd1 + 4, 2 * pwd1 + 6);
      int str3Len = Integer.parseInt(g_CH3_Len, 16);
//      System.out.println("pwd2str3Len==" + str3Len);
      str3Cip = encode.substring(2 * (pwd1 + 3) + 2 * str2Len, 2 * (3 + 
        pwd1 + str2Len + str3Len));
      this.bundle.putString("track3", str3Cip);
//      System.out.println("pwd2str3Cip==" + str3Cip);
      
      String pwdCip = encode.substring(
        2 * (3 + pwd1 + str2Len + str3Len), 2 * (3 + pwd1 + 
        str2Len + str3Len + 8));
      
      this.bundle.putString("pin", pwdCip);
      String amountCip = encode
        .substring(2 * (3 + pwd1 + str2Len + str3Len + 8), 
        2 * (3 + pwd1 + str2Len + str3Len + 24));
      
      this.bundle.putString("amount", amountCip);
      String cardNum = encode.substring(2 * (3 + pwd1 + str2Len + 
        str3Len + 24), 
        2 * (3 + pwd1 + str2Len + str3Len + 30));
      String cardLen = cardNum.substring(6, 8);
      String aa = cardNum.substring(6, 8);
      int bb = Integer.parseInt(aa, 16);
      

      StringBuilder builder = new StringBuilder();
      char[] array = cardNum.toCharArray();
      for (int i = 0; i < array.length; i++) {
        if (i == 6)
        {
          for (int j = 0; j < bb; j++) {
            builder.append("*");
          }
          i++;
        }
        else
        {
          builder.append(array[i]);
        }
      }
      this.bundle.putString("PlainAccount", builder.toString());
      

      String random = encode.substring(2 * (3 + pwd1 + str2Len + 
        str3Len + 30), 
        2 * (3 + pwd1 + str2Len + str3Len + 30 + 4));
      
      this.bundle.putString("random", random);
      String mac = encode.substring(2 * (3 + pwd1 + str2Len + str3Len + 
        30 + 4), 2 * (3 + pwd1 + str2Len + str3Len + 30 + 8));
      
      this.bundle.putString("mac", mac);
      




      this.bundle.putString("swipeState", "00");
    }
    else
    {
      this.bundle.putString("swipeState", "01");
    }
  }
  
  public String splitSendMacStr(String macData)
    throws InterruptedException, TimeoutException
  {
    int leng = macData.length();
    
    int SENDLEN = 128;
    

    int num = leng % 128;
    int start = 0;
    int end = 128;
    
    int i = 0;
    for (i = 0; i < leng / 128; i++)
    {
      if (i == 0) {
        Thread.sleep(300L);
      }
      String hexStr = macData.substring(start, end);
      


      byte[] result = parseHexStr2Byte(hexStr);
      
      SendingMac(result, result.length, 8000, i);
      Thread.sleep(300L);
      start = end;
      end += 128;
    }
    if (num != 0)
    {
      String hexStr = macData.substring(start, leng);
      byte[] result = parseHexStr2Byte(hexStr);
      SendingMac(result, result.length, 8000, i);
    }
    else
    {
      byte[] result = parseHexStr2Byte("00");
      SendingMac(result, 0, 8000, i);
    }
    return macData;
  }
  
  public void SendingMac(byte[] Data, int Datalength, int millis, int k)
    throws InterruptedException, TimeoutException
  {
    String Received = null;
    int i = 0;
    byte[] my_cmdbuf = null;
    my_cmdbuf = new byte[Datalength + 7];
    my_cmdbuf[0] = -86;
    my_cmdbuf[1] = ((byte)(Datalength + 3));
    my_cmdbuf[2] = 14;
    my_cmdbuf[3] = ((byte)Datalength);
    my_cmdbuf[4] = ((byte)k);
    for (; i < Datalength; i++) {
      my_cmdbuf[(i + 5)] = Data[i];
    }
    my_cmdbuf[(i + 5)] = -18;
    my_cmdbuf[(i + 6)] = 0;
    my_cmdbuf[(i + 6)] = ((byte)Senddata_LRCcheck(my_cmdbuf));
    if (this.mSocket == null) {
      return;
    }
    try
    {
      OutputStream os = this.mSocket.getOutputStream();
      os.write(my_cmdbuf);
      
      os.flush();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
  
  public static boolean isDigit(String strNum)
  {
    return strNum.matches("[0-9,a-f,A-F]{1,}");
  }
  
  public interface OnBluetoothDataListener
  {
    void onReceiveData(String paramString, Bundle paramBundle, int paramInt);
  }
}

